<?php
namespace app\controllers;

use yii\filters\Cors;
use yii\rest\Controller;

class ApiController extends Controller
{
    public static function allowedDomains(): array
    {
        return [
            'localhost',
            'testapi.local'
            //'*',                        // star allows all domains
            //'http://test1.example.com',
            //'http://test2.example.com',
        ];
    }

    public function behaviors(): array
    {
        return array_merge(parent::behaviors(), [
            // For cross-domain AJAX request
            'corsFilter'  => [
                'class' => Cors::class,
                'cors'  => [
                    // restrict access to domains:
                    'Origin'                           => static::allowedDomains(),
                    'Access-Control-Request-Method'    => ['GET','POST','PATCH','PUT','DELETE'],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age'           => 3600,                 // Cache (seconds)
                    'Access-Control-Allow-Headers' => ['content-type'],
                    'Access-Control-Request-Headers' => ['*'],
                ],
            ],
        ]);
    }

    public function actions(): array
    {
        return [
            'options' => [
                'class' => 'yii\rest\OptionsAction',
            ],
        ];
    }
}
